# -*- coding: UTF-8 -*-
"""
copyright (c) 2009, paketka@gmail.com et. al
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

    * Redistributions of source code must retain the above copyright notice,
      this list of conditions and the following disclaimer.

    * Redistributions in binary form must reproduce the above copyright notice,
      this list of conditions and the following disclaimer in the documentation
      and/or other materials provided with the distribution.

    * Neither the name of the <ORGANIZATION> nor the names of its contributors
      may be used to endorse or promote products derived from this software
      without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""

from django.db import models
from django.db.models.signals import pre_save
from utils.slugify import slugify
import unicodedata      
import re

class AutoSlug(models.Model):
    """
    AutoSlug is parent for all classes, which want to have autocreated
    slugfield(s) from another models field(s). all slug fields will be
    unique.

    slug_mf is a dictinary, keys are SlugFields name in child model,
    values are tupples of strings with fieldnames to compose slug field
    value from. the dictionary below tells how to generate the slug
    field value from name and surname.
        { 'slug' : ('name', 'surname') }
    """
    slugs = {}
    slug_sep = '_'
    unique = ()


    class Meta:
        abstract = True


    def _stringToSlug(self, s):
        raw_data = s
        # normalze string as proposed on
        # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/251871 by
        # Aaron Bentley, 2006/01/02

        try:
            if type(raw_data) == type(u''):
                raw_data = unicodedata.normalize('NFKD', raw_data)
                raw_data = raw_data.encode('ascii', 'ignore')
            else:
                raw_data = raw_data.decode('utf-8', 'replace')
                raw_data = unicodedata.normalize('NFKD', raw_data)
                raw_data = raw_data.encode('ascii', 'ignore')
        except:
            pass

        rv = re.sub(r'[^a-z0-9-]+', self.slug_sep, raw_data.lower())
        return rv.strip(self.slug_sep)


    def _proposeSlug(self, fieldSet):
        retVal = ''
        for fieldName in fieldSet:
            try:
                retVal += self.__getattribute__(fieldName) + self.slug_sep
            except:
                retVal += self.__getattribute__(fieldName).__str__() + self.slug_sep

        return self._stringToSlug(retVal)


    def _makeItUnique(self, sender, proposal, slugFieldName):
        query = {
            slugFieldName + '__startswith' : proposal,
        }
        similarOnes = sender.objects.filter(**query).values(slugFieldName)
        similarOnes = [ elem[slugFieldName] for elem in similarOnes ]

        if not proposal in similarOnes:
            return proposal

        numbers = []

        for value in similarOnes:
            match = re.match(r'^%s%s(\d+)$' % (proposal, self.slug_sep), value)
            if match:
                numbers.append(int(match.group(1)))

        if len(numbers)==0:
            return "%s%s2" % (proposal, self.slug_sep)
        else:
            largest = sorted(numbers)[-1]
            return "%s%s%d" % (proposal, self.slug_sep, largest + 1)



    def generateSlug(self, sender):
        fields = self._meta.fields
        for slugName in self.slugs.keys():
            for field in fields:
                if isinstance(field, models.SlugField) and\
                    field.get_attname() == slugName:
                    proposal = self._proposeSlug(self.slugs[slugName])
                    slugVal = ''
                    if field.unique == True:
                        slugVal = self._makeItUnique(sender, proposal, slugName)
                    else:
                        slugVal = proposal
                    self.__setattr__(slugName, slugVal)
                    break


    def defineEmptySlugs(self, sender):
        fields = self._meta.fields
        for slugName in self.slugs.keys():
            for field in fields:
                if isinstance(field, models.SlugField) and\
                    field.get_attname() == slugName and\
                    self.__getattribute__(slugName) == None or\
                    len(self.__getattribute__(slugName)) == 0:
                    proposal = self._proposeSlug(self.slugs[slugName])
                    slugVal = ''
                    if field.unique == True:
                        slugVal = self._makeItUnique(sender, proposal, slugName)
                    else:
                        slugVal = proposal
                    self.__setattr__(slugName, slugVal)
                    break


    def makeSlug(self, sender):
        try:
            self._default_manager.get(pk = self._get_pk_val())
        except:
            self.generateSlug(sender)

        self.defineEmptySlugs(sender)
        
        return
            


def makeSlug(sender, instance, **kwargs):
    instance.makeSlug(sender)
    return

pre_save.connect(makeSlug, AutoSlug)
